'use client';

import { useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { userApi } from '@/services/api';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Separator } from '@/components/ui/separator';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { User, Settings, Lock, Calendar, Mail, Shield } from 'lucide-react';
import { toast } from 'sonner';

const updateProfileSchema = z.object({
  nickname: z.string().min(2, '昵称至少2个字符').max(50, '昵称最多50个字符'),
  realName: z.string().max(50, '真实姓名最多50个字符').optional(),
  phone: z.string().regex(/^1[3-9]\d{9}$/, '请输入正确的手机号').optional().or(z.literal('')),
});

const changePasswordSchema = z.object({
  current_password: z.string().min(1, '请输入当前密码'),
  new_password: z.string().min(6, '新密码至少6个字符'),
  confirm_password: z.string().min(1, '请确认新密码'),
}).refine((data) => data.new_password === data.confirm_password, {
  message: '两次输入的密码不一致',
  path: ['confirm_password'],
});

type UpdateProfileForm = z.infer<typeof updateProfileSchema>;
type ChangePasswordForm = z.infer<typeof changePasswordSchema>;

export default function ProfilePage() {
  const { user, refreshUser } = useAuth();
  const [isUpdating, setIsUpdating] = useState(false);
  const [isChangingPassword, setIsChangingPassword] = useState(false);
  const [passwordDialogOpen, setPasswordDialogOpen] = useState(false);

  const profileForm = useForm<UpdateProfileForm>({
    resolver: zodResolver(updateProfileSchema),
    defaultValues: {
      nickname: user?.nickname || '',
      realName: user?.realName || '',
      phone: user?.phone || '',
    },
  });

  const passwordForm = useForm<ChangePasswordForm>({
    resolver: zodResolver(changePasswordSchema),
    defaultValues: {
      current_password: '',
      new_password: '',
      confirm_password: '',
    },
  });

  // 组件挂载时刷新用户信息
  useEffect(() => {
    refreshUser();
  }, []);

  // 当用户信息加载后，更新表单默认值
  useEffect(() => {
    if (user) {
      profileForm.reset({
        nickname: user.nickname || '',
        realName: user.realName || '',
        phone: user.phone || '',
      });
    }
  }, [user, profileForm]);

  const handleUpdateProfile = async (data: UpdateProfileForm) => {
    if (!user) return;
    
    setIsUpdating(true);
    try {
      await userApi.updateCurrentUser(data);
      await refreshUser();
      toast.success('个人信息更新成功');
    } catch (error: any) {
      toast.error(error.response?.data?.message || '更新失败');
    } finally {
      setIsUpdating(false);
    }
  };

  const handleChangePassword = async (data: ChangePasswordForm) => {
    setIsChangingPassword(true);
    try {
      await userApi.changePassword({
        oldPassword: data.current_password,
        newPassword: data.new_password,
      });
      toast.success('密码修改成功');
      setPasswordDialogOpen(false);
      passwordForm.reset();
    } catch (error: any) {
      toast.error(error.response?.data?.message || '密码修改失败');
    } finally {
      setIsChangingPassword(false);
    }
  };

  if (!user) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    );
  }

  return (
    <div className="container mx-auto py-6 space-y-6">
      <div className="flex items-center space-x-2">
        <User className="h-6 w-6" />
        <h1 className="text-2xl font-bold">个人资料</h1>
      </div>

      <div className="grid gap-6 md:grid-cols-3">
        {/* 用户信息卡片 */}
        <Card className="md:col-span-1">
          <CardHeader className="text-center">
            <Avatar className="h-20 w-20 mx-auto">
              <AvatarImage src={user.avatar} alt={user.username || 'User'} />
              <AvatarFallback className="text-lg">
                {user.username?.charAt(0).toUpperCase() || 'U'}
              </AvatarFallback>
            </Avatar>
            <CardTitle className="mt-4">{user.username || '未知用户'}</CardTitle>
            <CardDescription>{user.email || '未设置邮箱'}</CardDescription>
            <div className="flex justify-center mt-2">
              <Badge variant={user.is_admin ? 'default' : 'secondary'}>
                {user.is_admin ? '管理员' : '普通用户'}
              </Badge>
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center space-x-2 text-sm text-muted-foreground">
              <Calendar className="h-4 w-4" />
              <span>注册时间: {user.createdAt ? (typeof window !== 'undefined' ? new Date(user.createdAt).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }) : new Date(user.createdAt).toISOString().split('T')[0]) : '未知'}</span>
            </div>
            <div className="flex items-center space-x-2 text-sm text-muted-foreground">
              <Settings className="h-4 w-4" />
              <span>最后登录: {user.lastLogin ? (typeof window !== 'undefined' ? new Date(user.lastLogin).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }) : new Date(user.lastLogin).toISOString().split('T')[0]) : '从未登录'}</span>
            </div>
            {user.is_admin && (
              <div className="flex items-center space-x-2 text-sm text-muted-foreground">
                <Shield className="h-4 w-4" />
                <span>管理员权限</span>
              </div>
            )}
          </CardContent>
        </Card>

        {/* 编辑资料表单 */}
        <Card className="md:col-span-2">
          <CardHeader>
            <CardTitle>编辑资料</CardTitle>
            <CardDescription>
              更新您的个人信息
            </CardDescription>
          </CardHeader>
          <CardContent>
            {/* 只读邮箱信息 */}
            <div className="mb-4 p-3 bg-muted rounded-md">
              <div className="flex items-center space-x-2 text-sm">
                <Mail className="h-4 w-4" />
                <span className="font-medium">邮箱:</span>
                <span>{user?.email}</span>
                <Badge variant="secondary" className="text-xs">不可修改</Badge>
              </div>
            </div>
            
            <Form {...profileForm}>
              <form onSubmit={profileForm.handleSubmit(handleUpdateProfile)} className="space-y-4">
                <FormField
                  control={profileForm.control}
                  name="nickname"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>昵称</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入昵称" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={profileForm.control}
                  name="realName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>真实姓名</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入真实姓名（可选）" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={profileForm.control}
                  name="phone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>手机号</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入手机号（可选）" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <div className="flex space-x-4">
                  <Button type="submit" disabled={isUpdating}>
                    {isUpdating ? '更新中...' : '保存更改'}
                  </Button>
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => profileForm.reset()}
                  >
                    重置
                  </Button>
                </div>
              </form>
            </Form>

            <Separator className="my-6" />

            {/* 修改密码 */}
            <div className="space-y-4">
              <div>
                <h3 className="text-lg font-medium">安全设置</h3>
                <p className="text-sm text-muted-foreground">
                  管理您的账户安全
                </p>
              </div>
              
              <Dialog open={passwordDialogOpen} onOpenChange={setPasswordDialogOpen}>
                <DialogTrigger asChild>
                  <Button variant="outline" className="w-full sm:w-auto">
                    <Lock className="h-4 w-4 mr-2" />
                    修改密码
                  </Button>
                </DialogTrigger>
                <DialogContent>
                  <DialogHeader>
                    <DialogTitle>修改密码</DialogTitle>
                    <DialogDescription>
                      请输入当前密码和新密码
                    </DialogDescription>
                  </DialogHeader>
                  <Form {...passwordForm}>
                    <form onSubmit={passwordForm.handleSubmit(handleChangePassword)} className="space-y-4">
                      <FormField
                        control={passwordForm.control}
                        name="current_password"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>当前密码</FormLabel>
                            <FormControl>
                              <Input type="password" placeholder="请输入当前密码" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={passwordForm.control}
                        name="new_password"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>新密码</FormLabel>
                            <FormControl>
                              <Input type="password" placeholder="请输入新密码" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={passwordForm.control}
                        name="confirm_password"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>确认新密码</FormLabel>
                            <FormControl>
                              <Input type="password" placeholder="请再次输入新密码" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <DialogFooter>
                        <Button
                          type="button"
                          variant="outline"
                          onClick={() => setPasswordDialogOpen(false)}
                        >
                          取消
                        </Button>
                        <Button type="submit" disabled={isChangingPassword}>
                          {isChangingPassword ? '修改中...' : '确认修改'}
                        </Button>
                      </DialogFooter>
                    </form>
                  </Form>
                </DialogContent>
              </Dialog>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}